package com.ruoyi.jt808.util;

import io.netty.buffer.ByteBuf;

public class PacketSplitDetector {

    /**
     * 检查数据包是否完整
     */
    public static boolean isCompletePacket(ByteBuf buffer) {
        if (buffer.readableBytes() < 2) {
            return false; // 数据太少，不完整
        }

        buffer.markReaderIndex();

        try {
            // 检查起始标志
            if (buffer.readByte() != 0x7E) {
                return false;
            }

            // 检查是否有足够的数据读取消息头
            if (buffer.readableBytes() < 11) {
                return false;
            }

            // 读取消息体长度
            buffer.skipBytes(2); // 跳过消息ID
            short msgBodyProps = buffer.readShort();
            int bodyLength = msgBodyProps & 0x3FF;

            // 计算完整包长度
            int totalLength = 1 + 12 + bodyLength + 1 + 1;

            // 检查是否有足够的数据
            return buffer.readableBytes() + 1 >= totalLength - 1;

        } finally {
            buffer.resetReaderIndex();
        }
    }

    /**
     * 获取完整数据包长度
     */
    public static int getPacketLength(ByteBuf buffer) {
        if (buffer.readableBytes() < 13) {
            return -1; // 数据不足
        }

        buffer.markReaderIndex();

        try {
            // 跳过起始标志
            if (buffer.readByte() != 0x7E) {
                return -1;
            }

            // 读取消息体长度
            buffer.skipBytes(2); // 跳过消息ID
            short msgBodyProps = buffer.readShort();
            int bodyLength = msgBodyProps & 0x3FF;

            return 1 + 12 + bodyLength + 1 + 1;

        } finally {
            buffer.resetReaderIndex();
        }
    }
}